package cn.wzg.fragmentbase;

import android.os.Bundle;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

public class Activity2Fragment extends AppCompatActivity {
    private FragmentManager fragmentManager;
    private FragmentTransaction transaction;
    private Fragment fragment1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_2_fragment);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
        //获得FragmentManager对象
        fragmentManager = getSupportFragmentManager();
        //开启事务，获得FragmentTransaction对象
        transaction = fragmentManager.beginTransaction();
        //---------------------第一种方法----------------------------
        //创建需要添加的Fragment
        fragment1 = new DataFragment();
        // 步骤4:创建Bundle对象
        // 作用:存储数据，并传递到Fragment中
        Bundle bundle = new Bundle();
        // 步骤5:往bundle中添加数据
        bundle.putString("param1", "Zzuli");
        bundle.putString("param2", "I love you!");
        // 步骤6:把数据设置到Fragment中
        fragment1.setArguments(bundle);
        //----------------------------------------------------------
        //第二种方法：直接调用封装好的方法创建Fragment
        //fragment1=DataFragment.newInstance("Zzuli"," I love you!");

        //向容器内添加或替换碎片，默认情况下为LeftFragment
        transaction.replace(R.id.main,fragment1);
        //提交事务
        transaction.commit();
    }
}